/**************************************************************************
*   Copyleft 2009 by        											  *
*	Iwanicki Krzysztof													  *
*   <www.gamma.mini.pw.edu.pl/~iwanickik>		                          *
*                                                                         *
*   This program is free software; you can redistribute it and/or modify  *
*   it under the terms of the GNU General Public License as published by  *
*   the Free Software Foundation; either version 2 of the License, or     *
*   (at your option) any later version.                                   *
*                                                                         *
*   This program is distributed in the hope that it will be useful,       *
*   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
*   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
*   GNU General Public License for more details.                          *
***************************************************************************/
#include "./vGlFrustum.h"
#include "GL/glew.h"

namespace Vendetta {
	vGlFrustum::vGlFrustum(): vFrustum() {
	
	}
	
	vGlFrustum::~vGlFrustum() {
	
	}

	vVoid vGlFrustum::Extract() {
		vMatrix4D mv;			// Model view matrix
		vMatrix4D proj;			// Projection matrix
		vMatrix4D clip;			// Clipping frustum matrix (equals: proj * mv)

		// Retrieve matrices and viewport from OpenGL
#ifdef	V_DOUBLE_PRECISION
		glGetDoublev(GL_MODELVIEW_MATRIX, (vReal*) &mv);
		glGetDoublev(GL_PROJECTION_MATRIX, (vReal*) &proj);
#else 
		glGetFloatv(GL_MODELVIEW_MATRIX, (vReal*) &mv);
		glGetFloatv(GL_PROJECTION_MATRIX, (vReal*) &proj);
#endif

		// Calculate multiplication of projection and model-view matrices
		clip = proj;
		clip *= mv;

		mPlanes[VTOP].Build(clip[0][3] - clip[0][1], clip[1][3] - clip[1][1], clip[2][3] - clip[2][1], clip[3][3] - clip[3][1]);
		mPlanes[VBOTTOM].Build(clip[0][3] + clip[0][1], clip[1][3] + clip[1][1], clip[2][3] + clip[2][1], clip[3][3] + clip[3][1]);
		mPlanes[VLEFT].Build(clip[0][3] + clip[0][0], clip[1][3] + clip[1][0], clip[2][3] + clip[2][0], clip[3][3] + clip[3][0]);
		mPlanes[VRIGHT].Build(clip[0][3] - clip[0][0], clip[1][3] - clip[1][0], clip[2][3] - clip[2][0], clip[3][3] - clip[3][0]);
		mPlanes[VNEAR].Build(clip[0][3] + clip[0][2], clip[1][3] + clip[1][2], clip[2][3] + clip[2][2], clip[3][3] + clip[3][2]);
		mPlanes[VFAR].Build(clip[0][3] - clip[0][2], clip[1][3] - clip[1][2], clip[2][3] - clip[2][2], clip[3][3] - clip[3][2]);
	}
}